<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>持仓信息 - OKX 数据展示</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <style>
        body {
            background-color: #f4f7fa;
            font-family: Arial, sans-serif;
        }

        .navbar {
            background-color: #0c2461;
        }

        .card {
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .card-header {
            background-color: #0c2461;
            color: #212529;
            border-radius: 10px 10px 0 0;
            padding: 15px;
            font-weight: bold;
        }

        .table th {
            background-color: #f1f2f6;
        }

        .positive {
            color: #2ed573;
            font-weight: bold;
        }

        .negative {
            color: #ff4757;
            font-weight: bold;
        }

        .empty-data {
            text-align: center;
            padding: 50px;
            background-color: #f8f9fa;
            border-radius: 5px;
            margin: 20px 0;
        }

        .refreshed-time {
            font-size: 12px;
            color: #6c757d;
            text-align: right;
            margin-top: 5px;
        }

        .badge-cross {
            background-color: #0c2461;
            color: white;
            padding: 0.35em 0.65em;
            border-radius: 0.25rem;
        }

        .badge-isolated {
            background-color: #27ae60;
            color: white;
            padding: 0.35em 0.65em;
            border-radius: 0.25rem;
        }

        .position-row:hover {
            background-color: rgba(12, 36, 97, 0.1);
        }

        .btn-edit-product {
            background-color: #1e90ff;
            border-color: #1e90ff;
            color: white;
        }

        .btn-edit-product:hover {
            background-color: #0077ea;
            border-color: #0077ea;
            color: white;
        }

        .btn-close-position {
            background-color: #ff4757;
            border-color: #ff4757;
            color: white;
        }

        .btn-close-position:hover {
            background-color: #ea4335;
            border-color: #ea4335;
            color: white;
        }
    </style>
</head>
<body>
<!-- 引入导航栏片段 -->
<div th:replace="fragments/navbar :: navbar"></div>

<!-- 产品信息侧边卡片 - 初始隐藏 -->
<div id="product-info-card" class="position-fixed" style="display: none; left: 20px; top: 80px; width: 320px; z-index: 1000;">
    <div class="card mb-3">
        <div class="card-header bg-primary text-white">
            产品信息
            <button type="button" class="btn-close float-end" aria-label="Close" onclick="hideProductInfoCard()"></button>
        </div>
        <div class="card-body">
            <div id="product-info-loading" class="text-center">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">加载产品信息...</p>
            </div>
            <div id="product-info-content" style="display: none;">
                <h6 class="mb-3">产品: <span id="info-instId"></span></h6>

                <div class="card mb-3">
                    <div class="card-header bg-light">全仓状态信息</div>
                    <div class="card-body">
                        <div class="row mb-2">
                            <div class="col-md-6">全仓多仓补仓次数:</div>
                            <div class="col-md-6 text-end fw-bold" id="info-crossLongReplenishCount">--</div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-6">全仓空仓补仓次数:</div>
                            <div class="col-md-6 text-end fw-bold" id="info-crossShortReplenishCount">--</div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-6">全仓多仓成本:</div>
                            <div class="col-md-6 text-end fw-bold" id="info-crossLongCost">--</div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-6">全仓空仓成本:</div>
                            <div class="col-md-6 text-end fw-bold" id="info-crossShortCost">--</div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-6">全仓转逐仓多仓成本:</div>
                            <div class="col-md-6 text-end fw-bold" id="info-crossToIsolatedLongCost">--</div>
                        </div>
                        <div class="row mb-2">
                            <div class="col-md-6">全仓转逐仓空仓价差:</div>
                            <div class="col-md-6 text-end fw-bold" id="info-crossToIsolatedShortPriceDiff">--</div>
                        </div>
                    </div>
                </div>
            </div>
            <div id="product-info-error" class="alert alert-danger d-none">
                获取产品状态信息失败
            </div>
        </div>
    </div>
</div>

<div class="container">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span>持仓信息</span>
            <div>
                <select id="account-select" class="form-select form-select-sm d-inline-block" style="width: 200px;">
                    <option value="">-- 全部产品 --</option>
                    <option th:each="account : ${accounts}"
                            th:value="${account.instId}"
                            th:text="${account.accountName + ' (' + account.instId + ')'}">
                    </option>
                </select>
                <span id="connection-status" class="badge bg-secondary ms-2">连接中...</span>
            </div>
        </div>
        <div class="card-body">
            <div class="alert alert-info">
                实时持仓信息数据，每10秒自动刷新。
            </div>

            <!-- 提示消息容器 -->
            <div id="notification-container"></div>

            <!-- 加载指示器 -->
            <div id="loadingIndicator" class="text-center my-3" style="display: none;">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <div>数据加载中，请稍候...</div>
            </div>

            <!-- 空数据提示 -->
            <div id="emptyMessage" style="display: none;" class="alert alert-warning text-center">
                无持仓数据
            </div>

            <div class="row">
                <!-- 表格区域 -->
                <div id="positions-container-column" class="col-md-12">
                    <div id="positions-container">
                        <div class="empty-data" id="empty-message">
                            <h4>无持仓数据</h4>
                            <p>当前账户没有任何持仓信息，或者正在加载数据...</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="refreshed-time">
                最后更新时间: <span id="last-update-time">-</span>
            </div>
        </div>
    </div>
</div>

<!-- 平仓确认模态框 -->
<div class="modal fade" id="closePositionModal" tabindex="-1" aria-labelledby="closePositionModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="closePositionModalLabel">确认平仓</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>您确定要平仓以下持仓吗？</p>
                <p><strong>产品:</strong> <span id="modal-instId"></span></p>
                <p><strong>方向:</strong> <span id="modal-posSide"></span></p>
                <p><strong>保证金模式:</strong> <span id="modal-mgnMode"></span></p>
                <p><strong>持仓量:</strong> <span id="modal-pos"></span></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmCloseBtn">确认平仓</button>
            </div>
        </div>
    </div>
</div>

<!-- 产品状态信息模态框 -->
<div class="modal fade" id="accountStatusModal" tabindex="-1" aria-labelledby="accountStatusModalLabel"
     aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="accountStatusModalLabel">产品状态信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="accountStatusLoading" class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">加载产品状态信息...</p>
                </div>

                <div id="accountStatusError" class="alert alert-danger d-none">
                    获取产品状态信息失败
                </div>

                <div id="accountStatusContent" class="d-none">
                    <h6 class="mb-3">产品: <span id="status-instId"></span></h6>

                    <div class="row">
                        <!-- 全仓信息 -->
                        <div class="col-md-6">
                            <div class="card mb-3">
                                <div class="card-header bg-light">全仓状态信息</div>
                                <div class="card-body">
                                    <div class="row mb-2">
                                        <div class="col-md-6">全仓多仓补仓次数:</div>
                                        <div class="col-md-6 text-end fw-bold" id="crossLongReplenishCount">--</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">全仓空仓补仓次数:</div>
                                        <div class="col-md-6 text-end fw-bold" id="crossShortReplenishCount">--</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">全仓多仓成本:</div>
                                        <div class="col-md-6 text-end fw-bold" id="crossLongCost">--</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">全仓空仓成本:</div>
                                        <div class="col-md-6 text-end fw-bold" id="crossShortCost">--</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">全仓转逐仓多仓成本:</div>
                                        <div class="col-md-6 text-end fw-bold" id="crossToIsolatedLongCost">--</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">全仓转逐仓空仓价差:</div>
                                        <div class="col-md-6 text-end fw-bold" id="crossToIsolatedShortPriceDiff">--
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                   <!--     &lt;!&ndash; 逐仓信息 &ndash;&gt;
                        <div class="col-md-6">
                            <div class="card mb-3">
                                <div class="card-header bg-light">逐仓状态信息</div>
                                <div class="card-body">
                                    <div class="row mb-2">
                                        <div class="col-md-6">逐仓多仓补仓次数:</div>
                                        <div class="col-md-6 text-end fw-bold" id="isolatedLongReplenishCount">&#45;&#45;</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">逐仓空仓补仓次数:</div>
                                        <div class="col-md-6 text-end fw-bold" id="isolatedShortReplenishCount">&#45;&#45;</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">逐仓多仓成本:</div>
                                        <div class="col-md-6 text-end fw-bold" id="isolatedLongCost">&#45;&#45;</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">逐仓空仓成本:</div>
                                        <div class="col-md-6 text-end fw-bold" id="isolatedShortCost">&#45;&#45;</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">是否转移逐仓多仓:</div>
                                        <div class="col-md-6 text-end fw-bold" id="isTransferIsolatedLong">&#45;&#45;</div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-6">是否转移逐仓空仓:</div>
                                        <div class="col-md-6 text-end fw-bold" id="isTransferIsolatedShort">&#45;&#45;</div>
                                    </div>
                                </div>
                            </div>
                        </div>
-->
                    </div>

                    <!-- 系统信息 -->
                    <div class="card">
                        <div class="card-header bg-light">系统信息</div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="row mb-2">
                                        <div class="col-md-6">创建时间:</div>
                                        <div class="col-md-6 text-end" id="createdAt">--</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="row mb-2">
                                        <div class="col-md-6">更新时间:</div>
                                        <div class="col-md-6 text-end" id="updatedAt">--</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <a id="editProductBtn" href="#" class="btn btn-primary">编辑产品</a>
            </div>
        </div>
    </div>
</div>

<footer class="container mt-5">
    <hr>
    <p class="text-center text-muted">&copy; 2023 OKX 数据展示系统</p>
</footer>

<script th:src="@{/js/bootstrap.bundle.min.js}"></script>
<script th:src="@{/js/sockjs.min.js}"></script>
<script th:src="@{/js/stomp.min.js}"></script>
<script>
    // CSRF令牌处理
    const csrfToken = document.cookie.replace(/(?:(?:^|.*;\s*)XSRF-TOKEN\s*\=\s*([^;]*).*$)|^.*$/, "$1");

    // 全局变量
    let stompClient = null;
    let connectionStatus = document.getElementById('connection-status');
    let emptyMessage = document.getElementById('empty-message');
    let positionsContainer = document.getElementById('positions-container');
    let lastUpdateTime = document.getElementById('last-update-time');
    let positions = [];
    let accountSelect = document.getElementById('account-select');
    // 保存当前选择的产品ID，用于在数据更新时保持过滤状态
    let currentSelectedInstId = '';
    let filteredPositions = []; // 保存过滤后的持仓数据

    // 平仓模态框
    let closePositionModal = new bootstrap.Modal(document.getElementById('closePositionModal'));
    let modalInstId = document.getElementById('modal-instId');
    let modalPosSide = document.getElementById('modal-posSide');
    let modalMgnMode = document.getElementById('modal-mgnMode');
    let modalPos = document.getElementById('modal-pos');
    let confirmCloseBtn = document.getElementById('confirmCloseBtn');
    let currentPosition = null;

    // 状态信息模态框
    const accountStatusModal = new bootstrap.Modal(document.getElementById('accountStatusModal'));
    const accountStatusLoading = document.getElementById('accountStatusLoading');
    const accountStatusError = document.getElementById('accountStatusError');
    const accountStatusContent = document.getElementById('accountStatusContent');
    const editProductBtn = document.getElementById('editProductBtn');

    // 页面加载时连接WebSocket
    document.addEventListener('DOMContentLoaded', function () {
        // 初始化连接
        connect();

        // 账户下拉框改变事件
        accountSelect.addEventListener('change', function () {
            const selectedValue = this.value;
            const selectedText = this.options[this.selectedIndex].text;
            console.log('产品选择变更为:', selectedValue, '显示文本:', selectedText);

            // 清空现有数据显示，表明正在加载
            positionsContainer.innerHTML = '';
            showEmptyMessage('加载中', '正在获取指定产品的持仓数据...');

            // 保存当前选择，即使为空字符串也保存
            currentSelectedInstId = selectedValue;

            // 显示当前选择的产品信息
            console.log('当前下拉框选项:');
            for (let i = 0; i < accountSelect.options.length; i++) {
                const option = accountSelect.options[i];
                console.log(`  [${i}] 值: ${option.value}, 文本: ${option.text}, 是否选中: ${option.selected}`);
            }

            // 显示加载状态
            showLoading(true);

            // 立即更新最后更新时间
            updateLastUpdateTime();

            console.log('更新过滤条件为:', currentSelectedInstId);

            // 强制立即更新一次数据
            fetchPositions();
        });
    });

    // 应用过滤条件
    function applyFilter() {
        console.log('应用过滤条件，当前选择:', currentSelectedInstId);

        if (!positions || positions.length === 0) {
            console.log('没有持仓数据可供过滤');
            showEmptyMessage('无持仓数据', '当前没有任何持仓信息，或者正在加载数据...');
            showLoading(false);
            return;
        }

        console.log('过滤前持仓数量:', positions.length);

        if (!currentSelectedInstId || currentSelectedInstId === '') {
            // 显示所有持仓
            console.log('显示所有持仓数据');
            filteredPositions = [...positions]; // 复制整个数组
        } else {
            // 过滤特定产品的持仓
            console.log('过滤产品ID:', currentSelectedInstId);

            // 提取产品基础名称（例如从BTC-USD-SWAP中提取BTC）
            const selectedBase = currentSelectedInstId.split('-')[0].toUpperCase();
            console.log('选择的基础产品:', selectedBase);

            // 检查是否包含USD或USDT
            const hasUSD = currentSelectedInstId.includes('USD');
            const hasUSDT = currentSelectedInstId.includes('USDT');

            filteredPositions = positions.filter(position => {
                if (!position.instId) return false;

                // 确保position.instId存在并且是字符串
                const posInstId = String(position.instId || '').toUpperCase();
                const posBase = posInstId.split('-')[0].toUpperCase();

                // 1. 尝试完全匹配
                const exactMatch = posInstId === currentSelectedInstId.toUpperCase();

                // 2. 尝试基础名称匹配（例如BTC）
                const baseMatch = posBase === selectedBase;

                // 3. 处理USD和USDT的变体
                let variantMatch = false;
                if (baseMatch) {
                    if (hasUSD && posInstId.includes('USDT')) {
                        variantMatch = true;
                    } else if (hasUSDT && posInstId.includes('USD-')) {
                        variantMatch = true;
                    }
                }

                const finalMatch = exactMatch || (baseMatch && (variantMatch || posInstId.includes(selectedBase)));

                console.log(`产品 ${posInstId} 匹配 ${currentSelectedInstId}: ${finalMatch} (完全匹配: ${exactMatch}, 基础匹配: ${baseMatch}, 变体匹配: ${variantMatch})`);
                return finalMatch;
            });
            console.log('过滤后持仓数量:', filteredPositions.length);
        }

        // 渲染过滤后的数据
        if (filteredPositions && filteredPositions.length > 0) {
            emptyMessage.style.display = 'none';
            renderPositionsTable(filteredPositions);
        } else {
            showEmptyMessage('无匹配持仓', `产品 ${currentSelectedInstId || '所有'} 没有任何持仓信息`);
        }

        // 更新显示时间
        updateLastUpdateTime();
        showLoading(false);
    }

    // 显示空数据消息
    function showEmptyMessage(title, message) {
        emptyMessage.style.display = 'block';
        emptyMessage.innerHTML = `<h4>${title}</h4><p>${message}</p>`;
    }

    // 建立WebSocket连接
    function connect() {
        connectionStatus.textContent = '连接中...';
        connectionStatus.className = 'badge bg-secondary ms-2';

        try {
            let socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);

            // 禁用STOMP调试日志
            stompClient.debug = null;

            stompClient.connect({}, function (frame) {
                connectionStatus.textContent = '已连接';
                connectionStatus.className = 'badge bg-success ms-2';
                console.log('WebSocket连接成功');

                // 订阅持仓信息
                stompClient.subscribe('/topic/positions', function (response) {
                    try {
                        console.log('WebSocket收到持仓数据');
                        // 保存原始数据
                        const newPositions = JSON.parse(response.body);
                        console.log('持仓数据总数:', newPositions.length, '条');

                        // 处理持仓数据
                        handlePositionsData(newPositions);
                    } catch (error) {
                        console.error('解析持仓数据失败:', error);
                        showEmptyMessage('数据错误', '处理持仓数据时发生错误，请刷新页面重试');
                    }
                });

                // 初始加载持仓数据
                fetchPositions();
            }, function (error) {
                connectionStatus.textContent = '连接失败';
                connectionStatus.className = 'badge bg-danger ms-2';
                console.error('连接失败:', error);

                // 即使WebSocket连接失败，也通过API获取数据
                fetchPositions();

                // 5秒后重新尝试连接
                setTimeout(connect, 5000);
            });
        } catch (e) {
            console.error('WebSocket连接异常:', e);
            connectionStatus.textContent = '连接失败';
            connectionStatus.className = 'badge bg-danger ms-2';

            // 通过API获取数据
            fetchPositions();

            // 10秒后重新尝试连接
            setTimeout(connect, 10000);
        }
    }

    // 通过API获取持仓数据
    function fetchPositions() {
        console.log('开始获取持仓数据...');
        showLoading(true);

        // 更新时间戳以显示正在请求新数据
        updateLastUpdateTime();

        fetch('/api/v2/positions')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('API获取持仓数据:', data.length, '条');
                // 打印获取到的持仓数据以便调试
                data.forEach(pos => console.log(`获取到持仓: ${pos.instId}, ${pos.posSide}, ${pos.pos}`));

                // 处理接收到的持仓数据
                handlePositionsData(data);
            })
            .catch(error => {
                console.error('获取持仓数据失败:', error);
                showEmptyMessage('获取数据失败', '无法从服务器获取持仓信息，请稍后再试...');
                showLoading(false);
            });
    }

    // 更新最后更新时间
    function updateLastUpdateTime() {
        const now = new Date();
        const timeStr = now.toLocaleString();
        lastUpdateTime.textContent = timeStr;
        console.log('最后更新时间已更新:', timeStr);
    }

    // WebSocket订阅回调处理持仓数据
    function handlePositionsData(positionsData) {
        // 更新全局持仓数据
        positions = positionsData;
        console.log('收到持仓数据:', positions.length, '条');

        // 显示持仓数据的详情，帮助调试
        positions.forEach(pos => {
            console.log(`持仓: ${pos.instId}, 方向: ${pos.posSide}, 数量: ${pos.pos}`);
        });

        // 应用过滤条件
        applyFilter();

        // 更新最后更新时间
        updateLastUpdateTime();

        // 隐藏加载状态
        showLoading(false);
    }

    // 渲染持仓表格
    function renderPositionsTable(positionsData) {
        // 创建表格
        let tableHTML = `
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>产品</th>
                                    <th>方向</th>
                                <th>持仓模式</th>
                                    <th>持仓量</th>
                                    <th>杠杆</th>
                                    <th>开仓均价</th>
                                <th>最新价</th>
                                <th>保证金</th>
                                    <th>未实现盈亏</th>
                                    <th>强平价</th>
                                <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>`;

        positionsData.forEach(function (position) {
            // 格式化未实现盈亏（保留两位小数，不四舍五入）
            const uplValue = truncateToDecimalPlaces(position.upl, 2);
            const uplClass = position.upl >= 0 ? 'positive' : 'negative';

            // 格式化强平价（保留四位小数，不四舍五入）
            const liqPxValue = position.liqPx ? truncateToDecimalPlaces(position.liqPx, 4) : '-';

            // 持仓方向文本
            let posSideText = '';
            if (position.posSide === 'long') {
                posSideText = '多头';
            } else if (position.posSide === 'short') {
                posSideText = '空头';
            } else if (position.posSide === 'net') {
                posSideText = position.pos >= 0 ? '多头' : '空头';
            }

            // 保证金模式
            let mgnModeHtml = '';
            if (position.mgnMode === 'cross') {
                mgnModeHtml = '<span class="badge badge-cross">全仓</span>';
            } else if (position.mgnMode === 'isolated') {
                mgnModeHtml = '<span class="badge badge-isolated">逐仓</span>';
            } else {
                mgnModeHtml = position.mgnMode;
            }

            // 使用data-instid属性存储产品ID，以便点击时使用
            tableHTML += `
                    <tr class="position-row" data-instid="${position.instId}" style="cursor: pointer;">
                            <td>${position.instId}</td>
                            <td>${posSideText}</td>
                        <td>${mgnModeHtml}</td>
                            <td>${position.pos}</td>
                            <td>${position.lever}x</td>
                            <td>${position.avgPx}</td>
                        <td>${position.last}</td>
                        <td>${position.mgnMode == 'isolated' ? position.margin.toFixed(2) : position.imr.toFixed(2)}</td>
                        <td class="${uplClass}">${uplValue} </td>
                        <td>${liqPxValue}</td>
                        <td>
                            <div class="d-flex gap-2">
                                <button class="btn btn-sm btn-edit-product"
                                        onclick="editProduct('${position.instId}'); event.stopPropagation();">
                                    编辑产品
                                </button>
                                <button class="btn btn-sm btn-close-position"
                                        onclick="showClosePositionModal('${position.instId}', '${position.posSide}', '${position.mgnMode}', '${position.pos}'); event.stopPropagation();">
                                    一键平仓
                                </button>
                            </div>
                        </td>
                        </tr>`;
        });

        tableHTML += `
                            </tbody>
                        </table>
                    </div>`;

        positionsContainer.innerHTML = tableHTML;

        // 添加行点击事件
        document.querySelectorAll('.position-row').forEach(row => {
            row.addEventListener('click', function() {
                const instId = this.getAttribute('data-instid');
                // 显示产品信息卡片
                showProductInfoCard(instId);
            });
        });
    }

    // 显示产品状态信息
    function showAccountStatus(instId) {
        console.log('显示产品状态信息:', instId);

        if (!instId) {
            showNotification('产品ID不能为空', 'warning');
            return;
        }

        // 重置模态框状态
        accountStatusLoading.classList.remove('d-none');
        accountStatusError.classList.add('d-none');
        accountStatusContent.classList.add('d-none');

        // 设置产品ID和编辑按钮链接
        document.getElementById('status-instId').textContent = instId;
        editProductBtn.href = `/accounts/edit?prefilledInstId=${encodeURIComponent(instId)}`;

        // 显示模态框
        accountStatusModal.show();

        // 获取产品状态信息
        fetch(`/api/v2/account-status?instId=${encodeURIComponent(instId)}`, {
            headers: {
                'X-XSRF-TOKEN': csrfToken
            },
            credentials: 'same-origin'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('获取产品状态信息成功:', data);

                if (data.code === 0) {
                    // 填充数据
                    const statusData = data.data;

                    // 全仓信息
                    const crossInfo = statusData.crossInfo || {};
                    document.getElementById('crossLongReplenishCount').textContent = crossInfo.crossLongReplenishCount || '--';
                    document.getElementById('crossShortReplenishCount').textContent = crossInfo.crossShortReplenishCount || '--';
                    document.getElementById('crossLongCost').textContent = crossInfo.crossLongCost || '--';
                    document.getElementById('crossShortCost').textContent = crossInfo.crossShortCost || '--';
                    document.getElementById('crossToIsolatedLongCost').textContent = crossInfo.crossToIsolatedLongCost || '--';
                    document.getElementById('crossToIsolatedShortPriceDiff').textContent = crossInfo.crossToIsolatedShortPriceDiff || '--';

                    // // 逐仓信息
                    // const isolatedInfo = statusData.isolatedInfo || {};
                    // document.getElementById('isolatedLongReplenishCount').textContent = isolatedInfo.isolatedLongReplenishCount || '--';
                    // document.getElementById('isolatedShortReplenishCount').textContent = isolatedInfo.isolatedShortReplenishCount || '--';
                    // document.getElementById('isolatedLongCost').textContent = isolatedInfo.isolatedLongCost || '--';
                    // document.getElementById('isolatedShortCost').textContent = isolatedInfo.isolatedShortCost || '--';
                    // document.getElementById('isTransferIsolatedLong').textContent = isolatedInfo.isTransferIsolatedLong ? '是' : '否';
                    // document.getElementById('isTransferIsolatedShort').textContent = isolatedInfo.isTransferIsolatedShort ? '是' : '否';

                    // 系统信息
                    document.getElementById('createdAt').textContent = formatDateTime(statusData.createdAt);
                    document.getElementById('updatedAt').textContent = formatDateTime(statusData.updatedAt);

                    // 显示内容区域
                    accountStatusLoading.classList.add('d-none');
                    accountStatusContent.classList.remove('d-none');

                    // 获取产品信息并设置编辑按钮
                    fetch(`/accounts/api/find-by-instid?instId=${encodeURIComponent(instId)}`, {
                        headers: {
                            'X-XSRF-TOKEN': csrfToken
                        },
                        credentials: 'same-origin'
                    })
                        .then(response => response.json())
                        .then(account => {
                            if (account && account.id) {
                                editProductBtn.href = `/accounts/edit?id=${account.id}`;
                            }
                        })
                        .catch(() => {
                            // 如果找不到产品，则保持默认的创建产品链接
                        });
                } else {
                    showAccountStatusError(data.msg || '获取产品状态信息失败');
                }
            })
            .catch(error => {
                console.error('获取产品状态信息失败:', error);
                showAccountStatusError('获取产品状态信息失败: ' + error.message);
            });
    }

    // 显示产品状态信息错误
    function showAccountStatusError(message) {
        accountStatusLoading.classList.add('d-none');
        accountStatusContent.classList.add('d-none');
        accountStatusError.classList.remove('d-none');
        accountStatusError.textContent = message;
    }

    // 格式化日期时间
    function formatDateTime(dateStr) {
        if (!dateStr) return '--';
        try {
            const date = new Date(dateStr);
            return date.toLocaleString();
        } catch (e) {
            return dateStr;
        }
    }

    // 小数位截断函数（不进行四舍五入）
    function truncateToDecimalPlaces(num, decimalPlaces) {
        if (!num) return '--';
        const numStr = num.toString();
        const decimalPointIndex = numStr.indexOf('.');

        if (decimalPointIndex === -1) {
            return numStr;
        }

        const truncated = numStr.substring(0, decimalPointIndex + decimalPlaces + 1);
        return truncated;
    }

    // 显示通知消息
    function showNotification(message, type = 'success') {
        // 创建通知元素
        const notificationElement = document.createElement('div');
        notificationElement.className = `alert alert-${type} alert-dismissible fade show`;
        notificationElement.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;

        // 添加到容器
        const container = document.getElementById('notification-container');
        container.appendChild(notificationElement);

        // 3秒后自动关闭
        setTimeout(() => {
            const alert = new bootstrap.Alert(notificationElement);
            alert.close();
        }, 3000);
    }

    // 显示平仓确认模态框
    function showClosePositionModal(instId, posSide, mgnMode, pos) {
        modalInstId.textContent = instId;
        modalPosSide.textContent = posSide === 'long' ? '多头' : '空头';
        modalMgnMode.textContent = mgnMode === 'cross' ? '全仓' : '逐仓';
        modalPos.textContent = pos;

        currentPosition = {
            instId: instId,
            posSide: posSide,
            mgnMode: mgnMode
        };

        closePositionModal.show();
    }

    // 确认平仓按钮点击事件
    confirmCloseBtn.addEventListener('click', function () {
        if (currentPosition) {
            closePosition(currentPosition.instId, currentPosition.posSide, currentPosition.mgnMode);
        }
    });

    // 发送平仓请求
    function closePosition(instId, posSide, mgnMode) {
        const formData = new FormData();
        formData.append('instId', instId);
        formData.append('posSide', posSide);
        formData.append('mgnMode', mgnMode);

        fetch('/api/v2/close-positions', {
            method: 'POST',
            headers: {
                'X-XSRF-TOKEN': csrfToken
            },
            body: formData,
            credentials: 'same-origin'
        })
            .then(response => response.json())
            .then(data => {
                closePositionModal.hide();

                if (data.code === 0 || data.code === '0') {
                    showNotification(`产品 ${instId} 平仓成功！`);
                    // 重新获取持仓数据
                    setTimeout(fetchPositions, 1000);
                } else {
                    showNotification(`平仓失败：${data.msg || '未知错误'}`, 'danger');
                }
            })
            .catch(error => {
                closePositionModal.hide();
                showNotification(`平仓请求失败：${error}`, 'danger');
            });
    }

    // 显示/隐藏加载指示器
    function showLoading(show) {
        const loadingElement = document.getElementById('loadingIndicator');
        if (loadingElement) {
            if (show) {
                loadingElement.style.display = 'block';
            } else {
                loadingElement.style.display = 'none';
            }
        }
    }

    // 显示产品信息卡片
    function showProductInfoCard(instId) {
        const productInfoCard = document.getElementById('product-info-card');
        const productInfoContent = document.getElementById('product-info-content');
        const productInfoLoading = document.getElementById('product-info-loading');
        const productInfoError = document.getElementById('product-info-error');
        const infoInstId = document.getElementById('info-instId');

        // 显示卡片
        productInfoCard.style.display = 'block';
        productInfoLoading.style.display = 'block';
        productInfoContent.style.display = 'none';
        productInfoError.classList.add('d-none');

        // 设置基础信息
        infoInstId.textContent = instId;

        // 调整表格容器的margin-left以腾出空间（考虑卡片宽度和边距）
        document.querySelector('.container').style.marginLeft = '360px';
        
        // 获取产品状态信息
        fetch(`/api/v2/account-status?instId=${encodeURIComponent(instId)}`, {
            headers: {
                'X-XSRF-TOKEN': csrfToken
            },
            credentials: 'same-origin'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('获取产品状态信息成功:', data);

                if (data.code === 0) {
                    // 填充数据
                    const statusData = data.data;

                    // 全仓信息
                    const crossInfo = statusData.crossInfo || {};
                    document.getElementById('info-crossLongReplenishCount').textContent = crossInfo.crossLongReplenishCount || '--';
                    document.getElementById('info-crossShortReplenishCount').textContent = crossInfo.crossShortReplenishCount || '--';
                    document.getElementById('info-crossLongCost').textContent = crossInfo.crossLongCost || '--';
                    document.getElementById('info-crossShortCost').textContent = crossInfo.crossShortCost || '--';
                    document.getElementById('info-crossToIsolatedLongCost').textContent = crossInfo.crossToIsolatedLongCost || '--';
                    document.getElementById('info-crossToIsolatedShortPriceDiff').textContent = crossInfo.crossToIsolatedShortPriceDiff || '--';

                    // 显示内容区域
                    productInfoLoading.style.display = 'none';
                    productInfoContent.style.display = 'block';
                } else {
                    showProductInfoError(data.msg || '获取产品状态信息失败');
                }
            })
            .catch(error => {
                console.error('获取产品状态信息失败:', error);
                showProductInfoError('获取产品状态信息失败: ' + error.message);
            });
    }

    // 隐藏产品信息卡片
    function hideProductInfoCard() {
        const productInfoCard = document.getElementById('product-info-card');
        productInfoCard.style.display = 'none';
        
        // 恢复表格容器的margin-left
        document.querySelector('.container').style.marginLeft = '';
    }

    // 显示产品信息卡片错误
    function showProductInfoError(message) {
        const productInfoLoading = document.getElementById('product-info-loading');
        const productInfoContent = document.getElementById('product-info-content');
        const productInfoError = document.getElementById('product-info-error');

        productInfoLoading.style.display = 'none';
        productInfoContent.style.display = 'none';
        productInfoError.classList.remove('d-none');
        productInfoError.style.display = 'block';
        productInfoError.textContent = message;
    }

    // 编辑产品
    function editProduct(instId) {
        // 默认先使用prefilledInstId方式
        let editUrl = `/accounts/edit?prefilledInstId=${encodeURIComponent(instId)}`;
        
        // 获取产品信息以获取正确的ID
        fetch(`/accounts/api/find-by-instid?instId=${encodeURIComponent(instId)}`, {
            headers: {
                'X-XSRF-TOKEN': csrfToken
            },
            credentials: 'same-origin'
        })
            .then(response => response.json())
            .then(account => {
                if (account && account.id) {
                    // 如果找到产品ID，使用id参数
                    editUrl = `/accounts/edit?id=${account.id}`;
                }
                // 跳转到编辑页面
                window.location.href = editUrl;
            })
            .catch(() => {
                // 如果API调用失败，使用默认链接
                window.location.href = editUrl;
            });
    }
</script>
</body>
</html>
